package com.zjitc.controller;

import com.zjitc.model.CartItem;
import com.zjitc.model.Product;
import com.zjitc.model.User;
import com.zjitc.service.CartService;
import com.zjitc.service.UserService;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/10 15:14
 * @description:
 */
@Controller
public class CartController {

  @Autowired
  CartService cartService;
  @Autowired
  UserService userService;

  @RequestMapping("/findMyCart")
  public String findMyCart(HttpSession session) {
    User user = (User) session.getAttribute("user");
    if (user == null) {
      return "/WEB-INF/user/login.jsp";
    }
    List<CartItem> list = cartService.findByUid(user.getUid());
    if(list.size()==0){
      return "/WEB-INF/user/cart.jsp";
    }

    session.setAttribute("list", list);


    Double price = 0.0;
    if (list != null) {
      for (CartItem i : list) {
        price = price + i.getProduct().getShop_price() * i.getQuantity();
      }
      session.setAttribute("total", price);
    }

    return "/WEB-INF/user/cart.jsp";

  }

  @RequestMapping("/addCart")
  public String addCart(HttpSession session,
      Product product,
      CartItem cartItem
      ) {
    User user = (User) session.getAttribute("user");
    if (user == null) {
      return "/WEB-INF/user/login.jsp";
    } else {
      cartItem.setProduct(product);
      cartItem.setUser(user);
      int count=cartService.addCart(cartItem);
      return "forward:findMyCart.do";
    }
  }

  @RequestMapping("/removeCart")
  public String removeCart(String cartid,HttpSession session){
     cartService.removeCart(cartid);
     session.removeAttribute("list");
     return "forward:findMyCart.do";
  }

  @RequestMapping("/clearCart")
  public String clearCart(HttpSession session){
    cartService.clearCart();
    session.removeAttribute("list");
    return "forward:findMyCart.do";
  }
}

